// 获取画布和上下文
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');

// 画布尺寸
const CANVAS_WIDTH = 800;
const CANVAS_HEIGHT = 600;
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;

// 玩家状态
let gold = 100;
const goldElement = document.getElementById('gold');
let position = '起始港口';
const positionElement = document.getElementById('position');

// 港口数据
const ports = [
    { name: '起始港口', x: 50, y: 50 },
    { name: '贸易港口', x: 700, y: 500 },
    { name: '冒险港口', x: 150, y: 500 }
];

// 船只属性
const shipRadius = 10;
let shipX = ports[0].x;
let shipY = ports[0].y;

// 绘制港口
function drawPorts() {
    ports.forEach(port => {
        ctx.beginPath();
        ctx.arc(port.x, port.y, 15, 0, Math.PI * 2);
        ctx.fillStyle = 'brown';
        ctx.fill();
        ctx.closePath();
        ctx.fillStyle = 'white';
        ctx.font = '14px Arial';
        ctx.fillText(port.name, port.x - 20, port.y - 20);
    });
}

// 绘制船只
function drawShip() {
    ctx.beginPath();
    ctx.arc(shipX, shipY, shipRadius, 0, Math.PI * 2);
    ctx.fillStyle = 'black';
    ctx.fill();
    ctx.closePath();
}

// 移动船只到指定港口
function moveShipToPort(port) {
    const dx = port.x - shipX;
    const dy = port.y - shipY;
    const distance = Math.sqrt(dx * dx + dy * dy);
    const speed = 2;
    const steps = Math.ceil(distance / speed);

    let step = 0;
    const intervalId = setInterval(() => {
        if (step < steps) {
            shipX += (dx / steps);
            shipY += (dy / steps);
            step++;
        } else {
            clearInterval(intervalId);
            position = port.name;
            positionElement.textContent = position;
        }
    }, 16);
}

// 处理港口点击事件
canvas.addEventListener('click', function (event) {
    const rect = canvas.getBoundingClientRect();
    const mouseX = event.clientX - rect.left;
    const mouseY = event.clientY - rect.top;

    ports.forEach(port => {
        const dx = mouseX - port.x;
        const dy = mouseY - port.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        if (distance < 15) {
            moveShipToPort(port);
        }
    });
});

// 主游戏循环
function gameLoop() {
    ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);

    drawPorts();
    drawShip();

    requestAnimationFrame(gameLoop);
}

// 初始化游戏
gameLoop();